﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Web.Mvc;
using BuildManager.Services.Interfaces;
using BuildManager.Data.Deployments;

namespace BuildManager.Site.App_Start
{
	public class ThreadConfig
	{
		public static void StartApplicationThreads()
		{
			var buildCheckThread = new Thread(BuildCheckThreadHandler);
			buildCheckThread.Start();
		}

		private static void BuildCheckThreadHandler()
		{
			var ms = 300 * 1000;
			var logService = DependencyResolver.Current.GetService<ILogService>();
			try
			{
				var configurationService = DependencyResolver.Current.GetService<IConfigurationService>();
				ms = configurationService.GetBuildCheckThreadSleepSeconds() * 1000;
			}
			catch(Exception x)
			{
				logService.LogError("BuildCheckThreadHandler.Configuration", x);
			}

			while (true)
			{
				try
				{
					var buildService = DependencyResolver.Current.GetService<IBuildService>();
					buildService.CheckAllQueuedBuilds();
					buildService.QueueAllWaitingBuilds();
					buildService.FailBuildsStagingForTooLong();
					buildService.FailBuildsRunningUnitTestsForTooLong();
					buildService.StageAllWaitingBuilds();
					buildService.CheckAllTestResults();
					//buildService.RunUnitTestsOnAllWaitingBuilds();
					
				}
				catch (Exception x)
				{
					logService.LogError("BuildCheckThreadHandler.WhileLoop", x);
				}
				Thread.Sleep(ms);
			}
		}
	}
}